package org.netty.udp.server.config;

import java.net.InetSocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

@Component("udpNettyServer")
public class UdpNettyServer {

	private Logger logger = LoggerFactory.getLogger(UdpNettyServer.class);
	
	// 配置服务端NIO线程组
	EventLoopGroup group = new NioEventLoopGroup();
	private Channel channel;

	public ChannelFuture bing(InetSocketAddress address) {
        ChannelFuture channelFuture = null;
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)  // 广播
                    .option(ChannelOption.SO_RCVBUF, 2048 * 1024)  // 设置UDP读缓冲区为2M
                    .option(ChannelOption.SO_SNDBUF, 1024 * 1024)  // 设置UDP写缓冲区为1M
                    .handler(new UdpServerChannelInit());

            channelFuture = b.bind(address).syncUninterruptibly();
            channel = channelFuture.channel();
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            if (null != channelFuture && channelFuture.isSuccess()) {
                logger.info("udp netty server start done.");
            } else {
                logger.error("udp netty server start error.");
            }
        }
        return channelFuture;
    }

    public void destroy() {
        if (null == channel) return;
        channel.close();
        group.shutdownGracefully();
    }

    public Channel getChannel() {
        return channel;
    }
	
}
